//
// Prob.cpp for Prob in /home/vriely/Work/Math/201
// 
// Made by 
// Login   <@epitech.net>
// 
// Started on  Mon Feb 20 11:26:15 2012 
// Last update Sun Feb 26 19:07:43 2012 
//

#include "Prob.hh"

#include <sstream>
#include <algorithm>
#include <iostream>

void	aff(const std::string&);

Prob::Prob()
{

}

double	Prob::getResult() const
{
  if (this->list_.size() > 0)
    return convertFromString<double>(this->list_.front());
  return 0;
}

Prob::Prob(const std::list<std::string>& list)
: list_(list)
{

}

void	Prob::setList(const std::list<std::string>& list)
{
  this->list_ = list;
}

void	Prob::probAll()
{
  std::for_each(this->list_.begin(), this->list_.end(), doProb);
}

void	Prob::probEt()
{
  std::list<std::string>::iterator	tmp;

  for (std::list<std::string>::iterator it = this->list_.begin();
      it != this->list_.end();
      ++it)
    {
      if ((*it) == "x")
	{
	  double				first = convertFromString<double>(*tmp);
	  double				second;
	  std::ostringstream			oss;
	  std::list<std::string>::iterator	itTmp;
	
	  itTmp = it;
	  it++;
	  second = convertFromString<double>(*it);
	  first *= second;
	  oss << first;
	  this->list_.erase(itTmp);
	  this->list_.erase(it);
	  this->list_.insert(tmp, oss.str());
	  this->list_.erase(tmp);
	}
    tmp = it;
  }
}

void	Prob::probOr()
{
  std::list<std::string>::iterator	tmp;

  for (std::list<std::string>::iterator it = this->list_.begin();
      it != this->list_.end();
      ++it)
  {
    if ((*it) == "+")
    {
      double				first = convertFromString<double>(*tmp);
      double				second;
      std::ostringstream			oss;
      std::list<std::string>::iterator	itTmp;

      itTmp = it;
      it++;
      second = convertFromString<double>(*it);
      first = (second + first - (second * first));
      oss << first;
      this->list_.erase(itTmp);
      this->list_.erase(it);
      this->list_.insert(tmp, oss.str());
      this->list_.erase(tmp);
    }
    tmp = it;
  }
}

void	doProb(std::string& str)
{
  if (str[0] >= '0' && str[0] <= '9')
  {
    std::ostringstream	oss;
    double		d;

    d = convertFromString<double>(str);
    d = ((5 * d) + 6 ) / (12 * d);
    oss << d;
    str = oss.str();
  }
  else if (str[0] == '-')
  {
    std::ostringstream	oss;
    double		d;

    d = convertFromString<double>(str);
    d = 1 - (((5 * (-d)) + 6) / (12 * (-d)));
    oss << d;
    str = oss.str();
  }
}

  template <typename T>
T	convertFromString(const std::string& str)
{
  std::istringstream	iss(str);
  T			val;

  iss >> val;
  return val;
}

